package exer;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author tongchen
 * @create 2023-02-08 16:06
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        //创建信号量
        Semaphore semaphore = new Semaphore(5);
        //创建任务
     Runnable runnable=new Runnable() {
            @Override
            public void run() {
                //消耗资源
                try {
                    semaphore.acquire();
                    System.out.println( Thread.currentThread().getName()+"获取到资源了");
                    //执行任务
                    System.out.println(Thread.currentThread().getName()+"在执行任务");
                    //释放资源
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"释放资源了");
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        };
     //通过for循环不断创建线程
        for (int i = 0; i <10 ; i++) {
             Thread thread=new Thread(runnable,i+"");
             thread.start();
        }


    }
}
